package com.ego.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ego.common.util.PageUtil;
import com.ego.common.vo.BaseSearchVo;
import com.ego.common.vo.PageVo;
import com.ego.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ego.product.dao.BrandDao;
import com.ego.product.po.Brand;
import com.ego.product.service.BrandService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: ego
 * @description 品牌对应实现类
 * @author KamTang
 * @date 2022-11-13 12:56:14
 */
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, Brand> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageVo<Brand> search(BaseSearchVo search) {
        LambdaQueryWrapper<Brand> query = Wrappers.<Brand>lambdaQuery()
                .like(search.getKeyword() != null, Brand::getName, search.getKeyword());
        Page<Brand> page = baseMapper.selectPage(Page.of(search.getPageNum(), search.getPageSize()), query);
        return PageUtil.toPage(page);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void updateCascade(Brand brand) {
        // 保证冗余字段的数据一致
        this.updateById(brand);
        if (StringUtils.isNotEmpty(brand.getName())) {
            // 同步更新其他关联表中的数据
            categoryBrandRelationService.updateByIdAndName(brand.getBrandId(), brand.getName());
        }
    }

}
